package com.ruoyi.cpsp.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.cpsp.mapper.*;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.service.EmployeeService;
import com.ruoyi.cpsp.service.EvaluateRecordDetailService;
import com.ruoyi.cpsp.service.EvaluateRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author neu.xiaojiacheng
 * @version 1.0
 * @date 2022/2/24 15:01
 */
@Service
@Transactional
public class EvaluateRecordServiceImpl implements EvaluateRecordService {

    @Autowired
    private EvaluateRecordMapper evaluateRecordMapper;

    @Autowired
    private RegulationTimesMapper regulationTimesMapper;

    @Autowired
    private EvaluateRecordToEmployeeMapper toEmployeeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private EvaluateRecordDetailService detailService;

    @Override
    public List<EvaluateRecord> selectEvaluateRecords(Integer year, Integer quarter) {
        return evaluateRecordMapper.selectEvaluateRecords(year, quarter);
    }

    @Override
    public List<EvaluateRecord> selectEvaluateRecordsByDepart(List<String> idCardList,Integer year, Integer quarter) {
        return evaluateRecordMapper.selectEvaluateRecordsByDepart(idCardList, year, quarter);
    }

    /**
     * 当一条新的违章添加到evaluate_record_detail时
     * evaluate_record表中需要重新统计违章记录。
     * 如果肇事者之前在同一个部门犯过同样的错误，就添加次数并修改关联人员和扣减比例。
     * 如果之前没有在一个部门犯过同样的错误，就添加该记录到表中。
     * @param detail
     * @return
     */
    @Override
    public AjaxResult insertEvaluateRecord(EvaluateRecordDetail detail) {

        // 得到员工的班组，判断违章员工所在班组是管理层还是普通员工。
        Integer teamGroupId = detail.getEmployeeGroup();
        TeamGroup teamGroup = teamGroupMapper.selectById(teamGroupId);
        boolean isManageTag = teamGroup != null && teamGroup.getTeamGroupName().contains("管理");

        int year = detail.getYear();
        int session = detail.getQuarter();
        int times = 1;
        EvaluateRecordEntity evaluateRecord = evaluateRecordMapper.checkTimes(year, session, detail.getEmployeeIdCard(),detail.getEmployeeDepart(), detail.getRegulationTypeId(), detail.getRegulationDetailId());
        // 先检查evaluate_record表中有没有同样的错误。
        if (evaluateRecord != null) {
            times = evaluateRecord.getTimes() + 1;
            // 在regulationDetailTimes那个表实现通过detailId获得最大次数。
            int maxTimes = regulationTimesMapper.maxTimesByDetailId(detail.getRegulationDetailId());
            evaluateRecord.setTimes(times);
            // 大于说明违章次数达到最大了，扣减比例也达到最大。
            if (times > maxTimes) {
                evaluateRecordMapper.updateByIdSelective(evaluateRecord);
                return AjaxResult.success("");
            }else {
                // 当次数不到最大值，还需要修改关联人员和比例。
                // 删除上次记录和关联人员信息。
                evaluateRecordMapper.deleteInfoById(evaluateRecord.getId());
                toEmployeeMapper.deleteInfoByRecordId(evaluateRecord.getId());
                evaluateRecord.setId(null);
                boolean flag = insertToTable(evaluateRecord, isManageTag);
                if (flag)
                    return AjaxResult.success("插入数据成功！");
                return AjaxResult.error("插入数据失败！");
            }
        }
        // 之前肇事者没有犯过这种违章。
        EvaluateRecordEntity record = new EvaluateRecordEntity();
        record.setYear(year);
        record.setQuarter(session);
        record.setEmployeeIdCard(detail.getEmployeeIdCard());
        record.setEmployeeDepart(detail.getEmployeeDepart());
        record.setTimes(times);
        record.setRegulationTypeId(detail.getRegulationTypeId());
        record.setRegulationDetailId(detail.getRegulationDetailId());
        record.setIsTakeEffect(true);
        boolean flag = insertToTable(record, isManageTag);
        if (flag)
            return AjaxResult.success("插入数据成功！");
        return AjaxResult.error("插入数据失败！");
    }
    // 用来实现当evaluate_record中添加一条有效的，需要改变关联人员的数据时。
    // 对evaluate_record和evaluate_record_to_employee两个表的操作。
    public boolean insertToTable(EvaluateRecordEntity record, boolean isManageTag) {
        List<String> employeeIdCards = new ArrayList<>();
        boolean flag = true;
        //System.out.println("record那里是"+record.toString());
        // 插入到evaluate_record表。
        int tag = evaluateRecordMapper.insertEvaluateRecord(record);
        System.out.println("tag："+tag);
        if (tag < 1) flag = false;
        // 将关联人员插入到evaluate_record_to_employee表中。
        int recordId = evaluateRecordMapper.selectCurrMaxEvaluateRecordKey();
        // 根据regulationDetailId和times找到每部分的扣减比例。
        RegulationTimes regulationTimes = regulationTimesMapper.selectByDetailIdAndTimes(record.getRegulationDetailId(), record.getTimes());
        EvaluateRecordToEmployee toEmployee = new EvaluateRecordToEmployee();
        EmployeeEntity employee = employeeMapper.selectByCard(record.getEmployeeIdCard());
        // 肇事者employee.
        if (regulationTimes.getPersonalProportion() > 0) {
            toEmployee.setEvaluateRecordId(recordId);
            toEmployee.setEmployeeIdCard(record.getEmployeeIdCard());
            toEmployee.setProportionOfPunishment(regulationTimes.getPersonalProportion());
            tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
            employeeIdCards.add(record.getEmployeeIdCard());
            if (tag < 1) flag = false;
            //System.out.println("肇事者："+toEmployee.getEmployeeIdCard());
        }
        if (isManageTag) {
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            return flag;
        }
        if (employee.getTeamGroup() != null) {
            // 与肇事者同部门同班组
            if (regulationTimes.getTeamGroupProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByTeamGroup(employee.getTeamGroup().getId()+"", employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                        TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                        if (!rel.getIdCard().equals(employee.getIdCard()) && (teamGroup.getBranchManagerId() == null || !teamGroup.getBranchManagerId().equals(rel.getIdCard())) && (teamGroup.getMainManagerId() == null || !teamGroup.getMainManagerId().equals(rel.getIdCard())) ) {// 筛选同一个班组
                            // 如果分管或者主管与肇事者在一个班组，则不加。
                            toEmployee.setEvaluateRecordId(recordId);
                            toEmployee.setEmployeeIdCard(rel.getIdCard());
                            toEmployee.setProportionOfPunishment(regulationTimes.getTeamGroupProportion());
                            tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                            employeeIdCards.add(rel.getIdCard());
                            if (tag < 1) flag = false;
                            //System.out.println("同部门同班组："+toEmployee.getEmployeeIdCard());
                        }
                    }
                }
            }
            // 与肇事者同部门不同班组。
            if (regulationTimes.getDepartmentProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByDepartment(employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                        TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                        if (rel.getTeamGroup()== null || !rel.getTeamGroup().equals(employee.getTeamGroup())) {
                            if((teamGroup.getBranchManagerId() == null || !teamGroup.getBranchManagerId().equals(rel.getIdCard())) && (teamGroup.getMainManagerId() == null || !teamGroup.getMainManagerId().equals(rel.getIdCard()))) {
                                toEmployee.setEvaluateRecordId(recordId);
                                toEmployee.setEmployeeIdCard(rel.getIdCard());
                                toEmployee.setProportionOfPunishment(regulationTimes.getDepartmentProportion());
                                tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                                employeeIdCards.add(rel.getIdCard());
                                if (tag < 1) flag = false;
                                //System.out.println("同部门不同班组："+toEmployee.getEmployeeIdCard());
                            }
                        }
                    }
                }
            }
            // 肇事者的分管
            if (regulationTimes.getBranchManagerProportion() > 0) {
                TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                if (teamGroup.getBranchManagerId() != null) {
                    toEmployee.setEvaluateRecordId(recordId);
                    toEmployee.setEmployeeIdCard(teamGroup.getBranchManagerId());// 得到的是idCard。
                    toEmployee.setProportionOfPunishment(regulationTimes.getBranchManagerProportion());
                    tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                    employeeIdCards.add(teamGroup.getBranchManagerId());
                    if (tag < 1) flag = false;
                    //System.out.println("分管："+toEmployee.getEmployeeIdCard());
                }

            }
            // 肇事者的主管
            if (regulationTimes.getMainManagerProportion() > 0) {
                TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                if (teamGroup.getMainManagerId() != null) {
                    toEmployee.setEvaluateRecordId(recordId);
                    toEmployee.setEmployeeIdCard(teamGroup.getMainManagerId());
                    toEmployee.setProportionOfPunishment(regulationTimes.getMainManagerProportion());
                    tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                    employeeIdCards.add(teamGroup.getMainManagerId());
                    if (tag < 1) flag = false;
                    //System.out.println("主管："+toEmployee.getEmployeeIdCard());
                }

            }
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            // 根据employeeIdCard找到关联人员。
            return flag;
        }else {
            //当员工没有班组时，设置部门扣减比例
            if (regulationTimes.getDepartmentProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByDepartment(employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                                if(!rel.getIdCard().equals(employee.getIdCard())){
                                    toEmployee.setEvaluateRecordId(recordId);
                                    toEmployee.setEmployeeIdCard(rel.getIdCard());
                                    toEmployee.setProportionOfPunishment(regulationTimes.getDepartmentProportion());
                                    tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                                    employeeIdCards.add(rel.getIdCard());
                                    if (tag < 1) flag = false;
                                    //System.out.println("没班组的员工的部门员工id:："+toEmployee.getEmployeeIdCard());
                                }
                    }
                }
            }
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            return flag;
        }
    }

    @Override
    public int selectCurrMaxEvaluateRecordKey() {
        return evaluateRecordMapper.selectCurrMaxEvaluateRecordKey();
    }

    @Override
    public List<EvaluateRecordCurrentQuarter> getMaxProp(Integer year, Integer quarter) {
        return evaluateRecordMapper.getMaxProp(year, quarter);
    }

    @Override
    public List<EvaluateRecordCurrentQuarter> selectMaxProp(Integer year, Integer quarter, List<String> employeeIdCards) {
        return evaluateRecordMapper.selectMaxProp(year, quarter, employeeIdCards);
    }

    @Override
    public int deleteInfoById(Integer evaluateRecordId) {
        return evaluateRecordMapper.deleteInfoById(evaluateRecordId);
    }

    @Override
    public EvaluateRecord selectRecordById(Integer evaluateRecordId) {
        return evaluateRecordMapper.selectRecordById(evaluateRecordId);
    }

    @Override
    public int updateByIdSelective(EvaluateRecordEntity evaluateRecordEntity) {
        return evaluateRecordMapper.updateByIdSelective(evaluateRecordEntity);
    }

    @Override
    public EvaluateRecordEntity checkTimes(Integer year, Integer quarter, String employeeIdCard, String employeeDepart, Integer regulationTypeId, Integer regulationDetailId) {
        return evaluateRecordMapper.checkTimes(year, quarter, employeeIdCard, employeeDepart, regulationTypeId, regulationDetailId);
    }

    public int getSeason(Date date) {
        int season = 0;
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int month = c.get(Calendar.MONTH);
        switch (month) {
            case Calendar.JANUARY:
            case Calendar.FEBRUARY:
            case Calendar.MARCH:
                season = 1;
                break;
            case Calendar.APRIL:
            case Calendar.MAY:
            case Calendar.JUNE:
                season = 2;
                break;
            case Calendar.JULY:
            case Calendar.AUGUST:
            case Calendar.SEPTEMBER:
                season = 3;
                break;
            case Calendar.OCTOBER:
            case Calendar.NOVEMBER:
            case Calendar.DECEMBER:
                season = 4;
                break;
            default:
                break;
        }
        return season;
    }
}
